package com.termux.app.api;

import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.TermuxConstants;

import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;

/**
 * BroadcastReceiver to receive custom broadcasts from Python scripts.
 * 
 * Usage in Python:
 *   import subprocess
 *   # 显示 Toast
 *   subprocess.run(["am", "broadcast", "-a", "com.termux.PYTHON_API", 
 *                   "--es", "action", "show_toast", 
 *                   "--es", "message", "Hello from Python"])
 *   
 *   # 显示对话框（通过通知实现，因为 BroadcastReceiver 无法直接显示对话框）
 *   subprocess.run(["am", "broadcast", "-a", "com.termux.PYTHON_API",
 *                   "--es", "action", "show_dialog",
 *                   "--es", "title", "标题",
 *                   "--es", "message", "Dialog from Python"])
 */
public class PythonApiReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = "PythonApiReceiver";
    private static final String CHANNEL_ID = "python_api_channel";
    
    public static final String ACTION_PYTHON_API = "com.termux.PYTHON_API";
    public static final String EXTRA_ACTION = "action";
    public static final String EXTRA_MESSAGE = "message";
    public static final String EXTRA_DATA = "data";
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_RESULT_ID = "result_id"; // 用于标识返回值文件
    public static final String RESULT_DIR = "python_api_results"; // 返回值存储目录

    @Override
    public void onReceive(Context context, Intent intent) {
        // 使用 Android Log 直接输出，确保能看到日志
        Log.e(LOG_TAG, "===========================================");
        Log.e(LOG_TAG, "PythonApiReceiver.onReceive() 被调用！");
        Log.e(LOG_TAG, "===========================================");
        
        if (intent == null) {
            Log.e(LOG_TAG, "错误: Received null intent");
            Logger.logError(LOG_TAG, "Received null intent");
            return;
        }
        
        Log.e(LOG_TAG, "Intent Action: " + intent.getAction());
        Log.e(LOG_TAG, "Intent Extras: " + (intent.getExtras() != null ? intent.getExtras().toString() : "null"));
        
        Logger.logInfo(LOG_TAG, "============================== PythonApiReceiver ===================================");
        Logger.logInfo(LOG_TAG, "Intent Received:\n" + IntentUtils.getIntentString(intent));
        Logger.logInfo(LOG_TAG, "Intent Action: " + intent.getAction());
        Logger.logInfo(LOG_TAG, "Intent Extras: " + (intent.getExtras() != null ? intent.getExtras().toString() : "null"));
        
        String action = intent.getStringExtra(EXTRA_ACTION);
        if (action == null) {
            Log.e(LOG_TAG, "错误: No action specified in intent");
            Log.e(LOG_TAG, "Available extras: " + (intent.getExtras() != null ? intent.getExtras().keySet().toString() : "null"));
            Logger.logError(LOG_TAG, "No action specified in intent");
            Logger.logError(LOG_TAG, "Available extras: " + (intent.getExtras() != null ? intent.getExtras().keySet().toString() : "null"));
            return;
        }
        
        Log.e(LOG_TAG, "处理操作: " + action);
        Logger.logInfo(LOG_TAG, "Processing action: " + action);
        
        // 获取result_id，如果提供了则会将返回值写入文件
        String resultId = intent.getStringExtra(EXTRA_RESULT_ID);
        
        switch (action) {
            case "show_toast":
                String message = intent.getStringExtra(EXTRA_MESSAGE);
                if (message != null) {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    Logger.logInfo(LOG_TAG, "Toast shown: " + message);
                    // 返回成功状态
                    if (resultId != null) {
                        writeResult(context, resultId, "success", "Toast已显示: " + message);
                    }
                } else {
                    Logger.logError(LOG_TAG, "show_toast action but no message provided");
                    if (resultId != null) {
                        writeResult(context, resultId, "error", "未提供消息内容");
                    }
                }
                break;
                
            case "show_dialog":
                // 由于 BroadcastReceiver 无法直接显示对话框，我们使用通知代替
                // 或者启动一个 Activity 来显示对话框
                String dialogTitle = intent.getStringExtra(EXTRA_TITLE);
                String dialogMessage = intent.getStringExtra(EXTRA_MESSAGE);
                if (dialogMessage != null) {
                    // 使用通知来显示消息（更可靠）
                    showNotification(context, 
                        dialogTitle != null ? dialogTitle : "Python 对话框", 
                        dialogMessage);
                    Logger.logInfo(LOG_TAG, "Dialog notification shown: " + dialogMessage);
                } else {
                    Logger.logError(LOG_TAG, "show_dialog action but no message provided");
                }
                break;
                
            case "vibrate":
                // 使用 Termux:API 的振动功能（如果已安装）
                try {
                    Intent vibrateIntent = new Intent("com.termux.api.Vibrate");
                    vibrateIntent.putExtra("duration_ms", 500);
                    context.sendBroadcast(vibrateIntent);
                    Logger.logInfo(LOG_TAG, "Vibration requested");
                } catch (Exception e) {
                    Logger.logError(LOG_TAG, "Failed to vibrate: " + e.getMessage());
                }
                break;
                
            case "notification":
                // 发送通知
                String notificationTitle = intent.getStringExtra(EXTRA_TITLE);
                String notificationText = intent.getStringExtra(EXTRA_MESSAGE);
                if (notificationText != null) {
                    showNotification(context, 
                        notificationTitle != null ? notificationTitle : "Python 通知", 
                        notificationText);
                    Logger.logInfo(LOG_TAG, "Notification sent: " + notificationText);
                    if (resultId != null) {
                        writeResult(context, resultId, "success", "通知已发送: " + notificationText);
                    }
                } else {
                    Logger.logError(LOG_TAG, "notification action but no message provided");
                    if (resultId != null) {
                        writeResult(context, resultId, "error", "未提供通知消息");
                    }
                }
                break;
                
            case "get_device_info":
                // 获取设备信息并返回
                String deviceInfo = getDeviceInfo(context);
                Logger.logInfo(LOG_TAG, "Device info requested: " + deviceInfo);
                if (resultId != null) {
                    writeResult(context, resultId, "success", deviceInfo);
                }
                break;
                
            case "calculate":
                // 示例：执行计算并返回结果
                String data = intent.getStringExtra(EXTRA_DATA);
                if (data != null) {
                    try {
                        // 简单的计算示例：假设data是 "5+3" 这样的表达式
                        String result = performCalculation(data);
                        Logger.logInfo(LOG_TAG, "Calculation result: " + result);
                        if (resultId != null) {
                            writeResult(context, resultId, "success", result);
                        }
                    } catch (Exception e) {
                        Logger.logError(LOG_TAG, "Calculation error: " + e.getMessage());
                        if (resultId != null) {
                            writeResult(context, resultId, "error", "计算错误: " + e.getMessage());
                        }
                    }
                } else {
                    if (resultId != null) {
                        writeResult(context, resultId, "error", "未提供计算数据");
                    }
                }
                break;
                
            default:
                Logger.logError(LOG_TAG, "Unknown action: " + action);
                if (resultId != null) {
                    writeResult(context, resultId, "error", "未知的操作: " + action);
                }
        }
    }
    
    /**
     * 将返回值写入文件，供Python脚本读取
     * @param context Context对象
     * @param resultId 唯一的结果ID
     * @param status 状态（success/error）
     * @param data 返回的数据
     */
    private void writeResult(Context context, String resultId, String status, String data) {
        try {
            // 使用Termux的HOME目录存储返回值
            File resultDir = new File(TermuxConstants.TERMUX_HOME_DIR_PATH, RESULT_DIR);
            if (!resultDir.exists()) {
                resultDir.mkdirs();
            }
            
            File resultFile = new File(resultDir, resultId + ".json");
            String jsonResult = String.format("{\"status\":\"%s\",\"data\":\"%s\"}", 
                status, data.replace("\"", "\\\"").replace("\n", "\\n"));
            
            FileWriter writer = new FileWriter(resultFile);
            writer.write(jsonResult);
            writer.close();
            
            Logger.logInfo(LOG_TAG, "Result written to: " + resultFile.getAbsolutePath());
        } catch (IOException e) {
            Logger.logError(LOG_TAG, "Failed to write result: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 获取设备信息
     */
    private String getDeviceInfo(Context context) {
        StringBuilder info = new StringBuilder();
        info.append("设备型号: ").append(Build.MODEL).append("\n");
        info.append("Android版本: ").append(Build.VERSION.RELEASE).append("\n");
        info.append("SDK版本: ").append(Build.VERSION.SDK_INT).append("\n");
        info.append("制造商: ").append(Build.MANUFACTURER).append("\n");
        return info.toString();
    }
    
    /**
     * 执行简单的计算（示例）
     */
    private String performCalculation(String expression) {
        // 这是一个简单的示例，实际使用时应该使用更安全的表达式解析器
        try {
            // 移除所有空格
            expression = expression.replaceAll("\\s+", "");
            
            // 简单的加法示例
            if (expression.contains("+")) {
                String[] parts = expression.split("\\+");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a + b);
                }
            }
            // 简单的减法示例
            else if (expression.contains("-") && !expression.startsWith("-")) {
                String[] parts = expression.split("-");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a - b);
                }
            }
            // 简单的乘法示例
            else if (expression.contains("*")) {
                String[] parts = expression.split("\\*");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    return String.valueOf(a * b);
                }
            }
            // 简单的除法示例
            else if (expression.contains("/")) {
                String[] parts = expression.split("/");
                if (parts.length == 2) {
                    double a = Double.parseDouble(parts[0]);
                    double b = Double.parseDouble(parts[1]);
                    if (b == 0) {
                        return "错误: 除数不能为0";
                    }
                    return String.valueOf(a / b);
                }
            }
            
            return "错误: 不支持的表达式格式";
        } catch (Exception e) {
            return "错误: " + e.getMessage();
        }
    }
    
    private void showNotification(Context context, String title, String message) {
        try {
            NotificationManager notificationManager = 
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            
            if (notificationManager == null) {
                Logger.logError(LOG_TAG, "NotificationManager is null");
                return;
            }
            
            // 创建通知渠道（Android 8.0+ 需要）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Python API Notifications",
                    NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setDescription("来自 Python 脚本的通知");
                notificationManager.createNotificationChannel(channel);
            }
            
            // 创建点击通知后打开的 Intent
            Intent intent = new Intent(context, TermuxActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                context, 0, intent, 
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
            
            // 创建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
            
            notificationManager.notify((int) System.currentTimeMillis(), builder.build());
            Logger.logInfo(LOG_TAG, "Notification created successfully");
        } catch (Exception e) {
            Logger.logError(LOG_TAG, "Failed to show notification: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

